package com.onec.service.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.onec.service.api.content.AuthConstants;
import com.onec.service.api.content.FilterContent;
import com.onec.service.api.enums.error.GatewayEnum;
import com.onec.service.api.exception.GatewayException;
import com.onec.service.gateway.config.WhiteListConfig;
import com.onec.service.gateway.enums.SourceEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/**
 * 白名单路径访问时需要移除JWT请求头
 * Created by macro on 2020/7/24.
 *
 * @author onec
 */
@Component
public class IgnoreUrlsRemoveJwtFilter implements WebFilter {

    @Autowired
    private WhiteListConfig whiteListConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        PathMatcher pathMatcher = new AntPathMatcher();
        //白名单路径移除JWT请求头
        List<String> ignoreUrls = whiteListConfig.getUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                request = exchange.getRequest().mutate().header(AuthConstants.JWT_TOKEN_HEADER, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        String source = exchange.getRequest().getHeaders().getFirst(FilterContent.AUTHORIZE_SOURCE);
        if (StrUtil.isNotEmpty(source)) {
            if (!SourceEnum.isInclude(source)) {
                throw new GatewayException(GatewayEnum.SOURCE_ERROR);
            }
            if (SourceEnum.isAgent(source)) {
                request = exchange.getRequest().mutate().header(AuthConstants.JWT_TOKEN_HEADER, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        // 如果是agent 請求 同樣移除
        return chain.filter(exchange);
    }


}
